package com.example.leetcode.juc.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HtmlParserImpl implements HtmlParser {

    List<List<Integer>> graph = new ArrayList<>();
    Map<String, Integer> map = new HashMap<>();
    Map<Integer, String> ids = new HashMap<>();
    String[] urls;

    public HtmlParserImpl(String[] urls, int[][] edges) {
        this.urls = urls;
        buildGraph(urls, edges);
        for (int i = 0; i < urls.length; i++) {
            map.put(urls[i], i);
            ids.put(i, urls[i]);
        }
    }

    private void buildGraph(String[] urls, int[][] edges) {
        for (int i = 0; i < urls.length; i++) {
            graph.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            int from = edge[0];
            int to = edge[1];
            graph.get(from).add(to);
        }
    }

    @Override
    public List<String> getUrls(String url) {
        int id = map.get(url);
        List<Integer> nodes = graph.get(id);
        List<String> res = new ArrayList<>();
        for (Integer node : nodes) {
            res.add(urls[node]);
        }
        return res;
    }
}
